package com.crazymaker.demo.hystrix;

import com.crazymaker.springcloud.demo.api.DemoApi;
import com.crazymaker.springcloud.demo.api.UAAUserApi;
import com.netflix.hystrix.*;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;

@Slf4j
public class IsolationStrategyDemo {

    private static final Integer COUNT = 5;

    @Test
    public void testThreadPoolIsolationStrategy() throws Exception{
        HystrixCommand.Setter setter1 = HystrixCommand.Setter
                .withGroupKey(HystrixCommandGroupKey.Factory.asKey("factory-1"))
                .andCommandKey(HystrixCommandKey.Factory.asKey("command-1"))
                .andThreadPoolKey(HystrixThreadPoolKey.Factory.asKey("threadpool-1"))
                .andCommandPropertiesDefaults(HystrixCommandProperties.Setter()
                        .withExecutionTimeoutEnabled(true)
                        .withExecutionTimeoutInMilliseconds(2000)
                )
                .andThreadPoolPropertiesDefaults(HystrixThreadPoolProperties.Setter()
                        .withCoreSize(5)
                        .withMaximumSize(5)
                );

        // 线程池1调用
        for (Integer i = 0; i < COUNT; i++) {
            new HttpGetterCommand(DemoApi.class, setter1)
                    .toObservable().subscribe((s)->{
               log.info("result:{}", s);
            });
        }

        // 线程池2调用
        HystrixCommand.Setter setter2 = HystrixCommand.Setter
                .withGroupKey(HystrixCommandGroupKey.Factory.asKey("factory-1"))
                .andCommandKey(HystrixCommandKey.Factory.asKey("command-1"))
                .andThreadPoolKey(HystrixThreadPoolKey.Factory.asKey("threadpool-2"))
                .andCommandPropertiesDefaults(HystrixCommandProperties.Setter()
                        .withExecutionTimeoutEnabled(true)
                        .withExecutionTimeoutInMilliseconds(2000)
                )
                .andThreadPoolPropertiesDefaults(HystrixThreadPoolProperties.Setter()
                        .withCoreSize(5)
                        .withMaximumSize(5)
                );

        for (Integer i = 0; i < COUNT; i++) {
            new HttpGetterCommand(UAAUserApi.class, setter2)
                    .toObservable().subscribe((s) -> {
                        log.info("result:{}", s);
            });
        }
        log.info("main执行完毕");
        Thread.sleep(0x7fffffff);
    }
}
